<?php
/**
 * Created by PhpStorm.
 * User: win10
 * Date: 2018/8/24
 * Time: 0:18
 */
namespace app\index\controller;
use EasyWeChat\Factory;
class Wechat{
    public function index(){

        $config = [
            'app_id' => 'wx74f52a333c7c0778',
            'secret' => 'dab4ada3292f273abb7529f0b79848a7',
            'token' => 'weixin',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        $app = Factory::officialAccount($config);
//
        //$response = $app->server->serve();

//        $app->base->getValidIps();
        ;
//        dump($app->base->getValidIps());
        //dump($response);

//        json_encode($object，JSON_FORCE_OBJECT);
// 将响应输出


        //接收 & 回复用户消息
        $app->server->push(function ($message) {
            return "您好！欢迎使用 EasyWeChat!";
        });
        $app->server->push(function ($message) {
//            dump($message);
            switch ($message['MsgType']) {
                case 'event':
                    return '收到事件消息';
                    break;
                case 'text':
                    return '收到文字消息';
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }

            // ...
        });
        $result = $app->qrcode->temporary('foo', 6 * 24 * 3600);
//        dump($result);
        $url = $app->qrcode->url($result['ticket']);


        $content = file_get_contents($url); // 得到二进制图片内容

        file_put_contents(__DIR__ . '/code.jpg', $content); // 写入文件
//        $app->broadcasting->sendText("大家好！欢迎使用 EasyWeChat。");
        // 将响应输出 (服务端验证通过)
        $response = $app->server->serve();
        dump($response);

        return $response;

    }
    public function test(){
        $n=1;
        $test1 = function($value)use ($n)
        {
            echo $value.' and '.$n;
        };

        $test1('HelloWorld');
    }
    public function traceHttp()
    {

        $content = date('Y-m-d H:i:s')."\nREMOTE_ADDR:".$_SERVER["REMOTE_ADDR"]."\nQUERY_STRING:".$_SERVER["QUERY_STRING"]."\n\n";

        if (isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug(trim($content));
            sae_set_display_errors(true);
        }else {
            $max_size = 100000;
            $log_filename = __DIR__ . "log.txt";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, $content, FILE_APPEND);
        }
    }

    /**
     * 服务端验证  接收用户发送过来的消息
     * @return $this
     */
    public function service(){
        $config = [
            'app_id' => 'wx74f52a333c7c0778',
            'secret' => 'dab4ada3292f273abb7529f0b79848a7',
            'token' => 'weixin',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        $app = Factory::officialAccount($config);

        // 服务端的作用呢，在整个微信开发中主要是负责
        // 接收用户发送过来的消息，还有 用户触发的一系列事件。
        $app->server->push(function ($message) {
            // $message['FromUserName'] // 用户的 openid
            // $message['MsgType'] // 消息类型：event, text....
            return "您好！欢迎使用 EasyWeChat";
        });

        // 将响应输出 (服务端验证通过)
        $response = $app->server->serve();
//        dump($response);

        //http://wuyeo2o.skydige.com/index/wechat/service?echostr=test
        return $response->send();

    }

    /**
     * 公众号用户管理
     */
    public function user_manger(){

        $config = [
            'app_id' => 'wx74f52a333c7c0778',
            'secret' => 'dab4ada3292f273abb7529f0b79848a7',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];


        //["openid"] => array(2) {
        //[0] => string(28) "o9-sc1HWgeFjX5QekoFzJHCj-fkY"
        //[1] => string(28) "o9-sc1K8Vb120F-HASpdUjpZqZyA"
        $app = Factory::officialAccount($config);
        $user = $app->user->list();
        //拿一个用户
        $user1 = $app->user->get('o9-sc1HWgeFjX5QekoFzJHCj-fkY');

        /*array(16) {
            ["subscribe"] => int(1)
            ["openid"] => string(28) "o9-sc1HWgeFjX5QekoFzJHCj-fkY"
            ["nickname"] => string(15) "长大的坚强"
            ["sex"] => int(1)
            ["language"] => string(5) "zh_CN"
            ["city"] => string(0) ""
            ["province"] => string(0) ""
            ["country"] => string(9) "喀麦隆"
            ["headimgurl"] => string(134) "http://thirdwx.qlogo.cn/mmopen/Lk0dRicxHCC6QmPgrZHFicic6zNX8kUpyIFksbVKgYMaq0BIRKH7r7xhS2o1TbjMldM2xzgTP4EYGK0XgVdrtr4Ka6tqw8tsuS9/132"
            ["subscribe_time"] => int(1535047585)
            ["remark"] => string(0) ""
            ["groupid"] => int(0)
            ["tagid_list"] => array(0) {
            }
            ["subscribe_scene"] => string(16) "ADD_SCENE_OTHERS"
            ["qr_scene"] => int(0)
            ["qr_scene_str"] => string(0) ""
        }*/
        //拿多个用户
        $users = $app->user->select(["o9-sc1HWgeFjX5QekoFzJHCj-fkY","o9-sc1K8Vb120F-HASpdUjpZqZyA"]);

        //修改用户备注
        $remarkmsg = "僵尸粉";
        $remark = $app->user->remark("o9-sc1HWgeFjX5QekoFzJHCj-fkY", $remarkmsg); // 成功返回boolean

        //拉黑用户
        $app->user->block('openidxxxxx');
        // 或者多个用户
        $app->user->block(['openid1', 'openid2', 'openid3']);

        //取消拉黑用户
        $app->user->unblock('openidxxxxx');
        // 或者多个用户
        $app->user->unblock(['openid1', 'openid2', 'openid3']);
        //获取黑名单
        $app->user->blacklist($beginOpenid = null); // $beginOpenid 可选
        dump($remark);
    }

}